package aliyun.cx.admin.service.impl;

import aliyun.cx.admin.entity.Permission;
import aliyun.cx.admin.entity.RolePermission;
import aliyun.cx.admin.entity.UserRole;
import aliyun.cx.admin.mapper.PermissionMapper;
import aliyun.cx.admin.mapper.RolePermissionMapper;
import aliyun.cx.admin.mapper.UserRoleMapper;
import aliyun.cx.admin.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限管理服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private final RolePermissionMapper rolePermissionMapper;
    private final UserRoleMapper userRoleMapper;

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        try {
            // 查询角色的权限ID列表
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(wrapper);
            
            if (rolePermissions.isEmpty()) {
                return List.of();
            }
            
            // 获取权限ID列表
            List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
            
            // 查询权限详情
            return listByIds(permissionIds);
        } catch (Exception e) {
            log.error("获取角色权限失败，角色ID: {}", roleId, e);
            return List.of();
        }
    }

    @Override
    public List<Permission> getPermissionsByUserId(Long userId) {
        try {
            // 查询用户的角色ID列表
            QueryWrapper<UserRole> userRoleWrapper = new QueryWrapper<>();
            userRoleWrapper.eq("user_id", userId);
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleWrapper);
            
            if (userRoles.isEmpty()) {
                return List.of();
            }
            
            // 获取角色ID列表
            List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
            
            // 查询这些角色的所有权限
            QueryWrapper<RolePermission> rolePermissionWrapper = new QueryWrapper<>();
            rolePermissionWrapper.in("role_id", roleIds);
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(rolePermissionWrapper);
            
            if (rolePermissions.isEmpty()) {
                return List.of();
            }
            
            // 获取权限ID列表（去重）
            List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .distinct()
                .collect(Collectors.toList());
            
            // 查询权限详情
            return listByIds(permissionIds);
        } catch (Exception e) {
            log.error("获取用户权限失败，用户ID: {}", userId, e);
            return List.of();
        }
    }

    @Override
    public Permission getPermissionByName(String permissionName) {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("name", permissionName);
            return getOne(wrapper);
        } catch (Exception e) {
            log.error("根据权限名称获取权限失败，权限名称: {}", permissionName, e);
            return null;
        }
    }

    @Override
    public boolean existsByName(String permissionName) {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("name", permissionName);
            return count(wrapper) > 0;
        } catch (Exception e) {
            log.error("检查权限名称是否存在失败，权限名称: {}", permissionName, e);
            return false;
        }
    }

    @Override
    public List<Permission> getPermissionsByType(String type) {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("permission_type", type);
            wrapper.orderByAsc("name");
            return list(wrapper);
        } catch (Exception e) {
            log.error("根据权限类型获取权限失败，类型: {}", type, e);
            return List.of();
        }
    }

    @Override
    public List<Permission> getPermissionsByResource(String resource) {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.like("name", resource); // 使用name字段模糊查询
            wrapper.orderByAsc("name");
            return list(wrapper);
        } catch (Exception e) {
            log.error("根据资源获取权限失败，资源: {}", resource, e);
            return List.of();
        }
    }

    @Override
    public List<Permission> getMenuPermissions() {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("permission_type", "ADMIN"); // 管理权限作为菜单权限
            wrapper.orderByAsc("name");
            return list(wrapper);
        } catch (Exception e) {
            log.error("获取菜单权限失败", e);
            return List.of();
        }
    }

    @Override
    public List<Permission> getActionPermissions() {
        try {
            QueryWrapper<Permission> wrapper = new QueryWrapper<>();
            wrapper.eq("permission_type", "USER"); // 用户权限作为操作权限
            wrapper.orderByAsc("name");
            return list(wrapper);
        } catch (Exception e) {
            log.error("获取操作权限失败", e);
            return List.of();
        }
    }

    @Override
    public boolean hasPermission(Long userId, String permissionName) {
        try {
            List<Permission> userPermissions = getPermissionsByUserId(userId);
            return userPermissions.stream()
                .anyMatch(permission -> permissionName.equals(permission.getName()));
        } catch (Exception e) {
            log.error("检查用户权限失败，用户ID: {}, 权限名称: {}", userId, permissionName, e);
            return false;
        }
    }

    @Override
    public boolean hasResourcePermission(Long userId, String resource, String action) {
        try {
            List<Permission> userPermissions = getPermissionsByUserId(userId);
            // 简化实现：根据权限名称包含资源和操作判断
            String expectedPermission = resource + ":" + action;
            return userPermissions.stream()
                .anyMatch(permission -> 
                    permission.getName().equals(expectedPermission) ||
                    permission.getName().contains(resource));
        } catch (Exception e) {
            log.error("检查用户资源权限失败，用户ID: {}, 资源: {}, 操作: {}", userId, resource, action, e);
            return false;
        }
    }
}